import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/Layout/index.vue'
console.log(import.meta, window.__MICRO_APP_BASE_ROUTE__, 'router-vue3-child')
const router = createRouter({
  history: createWebHistory(window.__MICRO_APP_BASE_ROUTE__ || '/'),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: Layout,
      redirect: '/home1',
      children: [
        {
          path: '/home1',
          name: 'Home',
          component: () => import('../views/HomeView.vue')
        },
        {
          path: '/home2',
          name: 'Home2',
          component: () => import('../views/Home2.vue')
        }
      ]
    }
  ]
})
if (window.__MICRO_APP_ENVIRONMENT__) {
  // 如果__MICRO_APP_BASE_ROUTE__为 `/基座应用基础路由/子应用基础路由/`，则应去掉`/基座应用基础路由`
  // 如果对这句话不理解，可以参考案例：https://github.com/micro-zoe/micro-app-demo-0.x
  const realBaseRoute = window.__MICRO_APP_BASE_ROUTE__

  router.beforeEach(() => {
    if (typeof window.history.state?.current === 'string') {
      window.history.state.current = window.history.state.current.replace(
        new RegExp(realBaseRoute, 'g'),
        ''
      )
    }
  })

  router.afterEach(() => {
    if (typeof window.history.state === 'object') {
      window.history.state.current = realBaseRoute + (window.history.state.current || '')
    }
  })
}
export default router
